/**
 * @fileoverview This is a file where undefinedVars checks are disabled.
 * @suppress {undefinedVars}
 * @suppress {duplicate}
 */
// the above is for the Google Closure Compiler ant task


var waitForJoin;
var newGameOpened = false;
try {
$(document).ready(function() {

    try {

    heartbeat();

    getNewOpenGames();
    getNewRunningGames();
    removeOldOpenGames();
    removeOldRunningGames();

    $("#lobbyButtons").on("click", "#newGameButton", startNewGame);
    console.log("added jquery.on click function to newGameButton");

    $("#cancelNewGameButton").click(function() {
//        $.post("cancelNewGame", {"id":localStorage.getItem("id")},
        $.post("cancelNewGame", {"token":localStorage.getItem("token")},
            function() {
                $("#newGameStarted").css("visibility", "hidden");
                $("#lobbyButtons").on("click", "#newGameButton", startNewGame);
                $("#lobbyLowerArea").on("click", "#joinGameBtn", joinGame);
                $("input[name='opponent']").removeAttr("disabled", "disabled");
                waitForJoin.abort();
                //waitForJoin = "aborted";
            });
    });

    $("#scoresButton").click(function() {
//        $("#viewCSS").attr("href", "highScores.css");
        document.location.replace("highScoresTemp.jsp?id=" + localStorage.getItem("id"));
//        updateRankings();
    });
    console.log("added click function to scoresbutton");

    $("#gameHistoryButton").click(function() {
        document.location.replace("replayChoice.jsp");

    });

    $("#logOutButton").click(function() {
//        $.get("logOut", {"id":localStorage.getItem("id")},
        $.get("logOut", {"token":localStorage.getItem("token")},
            function() {
                localStorage.removeItem("id");
                localStorage.removeItem("token");
                window.location.replace("login.jsp");
        });
    });

    $("#lobbyLowerArea").on("click", "#joinGameBtn", joinGame);

    $("#continueGameBtn").click(function() {
        document.location.replace("game.jsp?id=" + localStorage.getItem("id"));
    });

//    if ($("#viewCSS").attr("href") == "lobbyNewGame.css") {
//        $("#lobbyButtons").off("click", "#newGameButton", startNewGame);
//        $("#lobbyLowerArea").off("click", "#joinGameBtn", joinGame);
//    }


    } catch(e) {
        console.log("error inside document.ready");
    }
});

} catch (e) {
    console.log("exception caught with document.ready");
}

function heartbeat() {
    var id = localStorage.getItem("id");

//    $.get("heartbeat", {"id":id},
    var token = localStorage.getItem("token");
    $.get("heartbeat", {"token":token},
        function() {
            setTimeout("heartbeat()", 5000);
    });
}

function getNewOpenGames() {
//    $.get("getNewOpenGames", {"id":localStorage.getItem("id")},
    $.get("getNewOpenGames", {"token":localStorage.getItem("token")},
        function(data) {
            var id = data.id;
            var username = data.username;
            if (newGameOpened) {
                $("#chooseOpponent").append("<input type='radio' name='opponent' value='" + id +
                    "' class='opponentRadio' disabled='disabled'><span>  " + username + "</span></input><br />");
            } else {
                $("#chooseOpponent").append("<input type='radio' name='opponent' value='" + id +
                    "' class='opponentRadio'><span>  " + username + "</span></input><br />");
            }
            getNewOpenGames();
        }, "json");
}

function getNewRunningGames() {
//    $.get("getNewRunningGames", {"id":localStorage.getItem("id")},
    $.get("getNewRunningGames", {"token":localStorage.getItem("token")},
        function(data) {
            $("#currentGamesPairs").append("<p id='" + data.id1 + "VS" + data.id2 + "'>" + data.username1 + " VS " +
                data.username2 + "</p>");
            getNewRunningGames();
        }, "json");
}

function removeOldOpenGames() {
//    $.get("removeOldOpenGames", {"id":localStorage.getItem("id")},
    $.get("removeOldOpenGames", {"token":localStorage.getItem("token")},
        function(id) {
            var inputElement = "#chooseOpponent > input[value=" + id + "]";
            $(inputElement).next().remove();    // span element
            $(inputElement).next().remove();    // br element
            $(inputElement).remove();           // input element
            removeOldOpenGames();
        });
}

function removeOldRunningGames() {
//    $.get("removeOldRunningGames", {"id":localStorage.getItem("id")},
    $.get("removeOldRunningGames", {"token":localStorage.getItem("token")},
        function(IDvsID) {
            var pSelector = "#currentGamesPairs > p[id=" + IDvsID + "]";
            $(pSelector).remove();
            removeOldRunningGames();
        });
}

function startNewGame(event) {
    console.log("function startNewGame: starting a new game!");
//    $.post("startNewGame", {"id":localStorage.getItem("id")},
    $.post("startNewGame", {"token":localStorage.getItem("token")},
        function() {
            console.log("finished posting new game to server");
            $("#newGameStarted").css("visibility", "visible");
            $("#lobbyButtons").off("click", "#newGameButton", startNewGame);
            $("#lobbyLowerArea").off("click", "#joinGameBtn", joinGame);
            $("input[name='opponent']").attr("disabled", "disabled");
        });
//    waitForJoin = $.get("startNewGame", {"id":localStorage.getItem("id")},
    waitForJoin = $.get("startNewGame", {"token":localStorage.getItem("token")},
        function(data) {
            alert(data.username + " ühines sinu mänguga!");
            localStorage.setItem("opponent", "" + data.username);
            document.location.replace("game.jsp?id=" + localStorage.getItem("id"));
//            var done = true;
        }, "json");

//    while (true) {
//        var done = false;
//        waitForJoin = $.get("startNewGame", {"id":localStorage.getItem("id")},
//            function(data) {
//                if (data.username === "") {
//
//                } else {
//                    alert(data.username + " ühines sinu mänguga!");
//                    document.location.replace("game.jsp?id=" + localStorage.getItem("id"));
//                    done = true;
//                }
//
//            }, "json");
//        if (waitForJoin === "aborted" || done === true) {
//            break;
//        }
//    }
}


function joinGame(event) {
    console.log("function joinGame: joining a game!");
    var opponent = $("#chooseOpponent > input:checked").attr("value");
    var opponentUsername = $.trim($("#chooseOpponent > input:checked").next().html());
    if (opponent == undefined) {
        alert("Palun vali vastane, kellega soovid mängida.");
        return;
    }
//    $.post("joinGame", {"opponent": opponent, "id":localStorage.getItem("id")},
    $.post("joinGame", {"opponent": opponent, "token":localStorage.getItem("token")},
        function() {
            localStorage.setItem("opponent", opponentUsername);
            document.location.replace("game.jsp?id=" + localStorage.getItem("id"));
        }, "json");
}

